<?php namespace system\model;
use houdunwang\model\Model;
class Category extends Model{
	//数据表
	protected $table = "category";

	//允许填充字段
	protected $allowFill = ['*'];
	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
	];

	//自动完成
	protected $auto=[
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];
//	获取数据
	public function getdata(){
//		p(Db::table('category')->get());
		return Arr::tree(Db::table('category')->get(), 'cname');
	}
	//顶级分类添加方法
	public  function add(){
		    return  $res=$this->save($_POST);
	}
//	添加子类
   public function  addson(){
      return $this->save($_POST);
     }


//	编辑
    public  function edit($cid){
//		p($_POST);die;
		$model=Category::find($cid); // 查找主键为1的数据
		   $model->cname = $_POST['cname'];
		   $model->title = $_POST['title'];
		   $model->cdes = $_POST['cdes'];
		   $model->ckeywords = $_POST['ckeywords'];
		   $model->pid = $_POST['pid'];
		   $model->csort = $_POST['csort'];
       $res= $model->save(); // 保存当前数据对象
//		p($res);die;
	}
//	获取可以修改的分类信息
     public  function  getfenlei($cid){
//         die;
         $data=Db::table('category')->get();
		 $cids=$this->findson($data,$cid);
		 $cids[]=$cid;
		 $res = $this->whereNotIn('cid',$cids)->get()->toArray();
		 return $res;
	 }

	//找所有子类的方法
	public function findson($data,$cid){
		static $arr=[];
         foreach($data as $k=>$v) {
			 if ($v['pid'] == $cid) {
				 $arr[] = $v['cid'];
				 $this->findson($data, $v['cid']);
			 }
		 }
         return $arr;
	}

	//删除方法
	public  function del($cid){
//		p(222);die;
		$pid=current(Db::table('Category')->where('cid',$cid)->get(['pid']));
//		将要删除的pid给它的儿子
			$this->where('pid',$cid )->update(['pid' => $pid['pid']]);
		// 删除数据
		return Category::delete($cid);
	}
	/*
	 * 获得所有的所有的分类信息
	 */
	public  function  getclasses(){
		return  Arr::tree($this->get()->toArray(), 'cname');
	}
}